package cn.wolfcode.trip.base.service.impl;

import cn.wolfcode.trip.base.domain.Personal;
import cn.wolfcode.trip.base.domain.PersonalContent;
import cn.wolfcode.trip.base.mapper.PersonalContentMapper;
import cn.wolfcode.trip.base.mapper.PersonalMapper;
import cn.wolfcode.trip.base.query.QueryObject;
import cn.wolfcode.trip.base.service.IPersonalService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class PersonalServiceImpl implements IPersonalService {
    @Autowired
    private PersonalMapper personalMapper;
    @Autowired
    private PersonalContentMapper contentMapper;

    public PageInfo<Personal> query(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize(), qo.getOrderBy());
        List<Personal> list = personalMapper.selectForList(qo);
        return new PageInfo<>(list);
    }

    public void saveOrUpdate(Personal entity) {
        //设置发布时间
        if (entity.getState() == Personal.STATE_RELEASE) {
            entity.setReleaseTime(new Date());
        }
        //文章内容的主键关联
        PersonalContent personalContent = entity.getPersonalContent();
        if (entity.getId() == null) {
            //设置创建时间
            entity.setCreateTime(new Date());
            personalMapper.insert(entity);
            personalContent.setId(entity.getId());
            contentMapper.insert(personalContent);
        } else {
            personalMapper.updateByPrimaryKey(entity);
            personalContent.setId(entity.getId());
            contentMapper.updateByPrimaryKey(personalContent);
        }
    }

    @Override
    public String getContentById(Long id) {
        return contentMapper.selectByPrimaryKey(id).getContent();
    }

   /* public List<Personal> list() {
        return personalMapper.selectEnable();
    }*/

    public Personal get(Long id) {
        //1:根据id查询到游记对象
        Personal aPersonal = personalMapper.selectByPrimaryKey(id);
        //2:根据游记的id查询内容对象,设置到游记中
        PersonalContent personalContent = contentMapper.selectByPrimaryKey(id);
        aPersonal.setPersonalContent(personalContent);
        return aPersonal;
    }

    @Override
    public Personal getPersonalByMaxDate(Long id) {
        return personalMapper.selectByMaxDate(id);
    }

}
